﻿using Bear.BLL;
using Bear.BLL.MapleStory;
using Bear.Library;
using Bear.Library.Util;
using Bear.Library.WinApi;
using Bear.Library.WinForm;
using Bear.Models;
using Emgu.CV;
using Emgu.CV.Structure;
using PeopleSimulator;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Bear.MapleStory
{

    public partial class MainForm : Form, INoticeForm
    {
        private int _LifeAndmagicCount = 0;

        private OptionForm _OptionForm = null;
        private AboutBox _AboutForm = null;

        public DataCenter DataCenter { get; set; }

        //Buff 计时器
        List<System.Timers.Timer> _BuffTimer = null;

        private CancellationTokenSource _CtsEatMagic = null;
        private CancellationTokenSource _CtsEatLife = null;
        private CancellationTokenSource _CtsAttack = null;


        #region 注册事件
        private void RegisterEvent()
        {
            CancellationTokenSource tokenSource = null;

            butStart.Click += (sender, e) =>
            {
                #region 开始

                Map map = this.cbMap.SelectedItem as Map;
                if (map == null)
                {
                    LoliMessageBox.Show(this, "请先选择打怪地图！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                this.DataCenter.CurrentPlayer = this.cbPlayer.SelectedItem as Player;
                if (this.DataCenter.CurrentPlayer == null)
                {
                    LoliMessageBox.Show(this, "请选择当前人物！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                tokenSource = new CancellationTokenSource();
                this.DisableControls(true);
                          

                Task task = Task.Factory.StartNew(delegate()
                {                 
                    try
                    {
                        Automatic Automatic = new BLL.MapleStory.Automatic();
                        Automatic.ShowMessage += ShowMessage;
                        while (true)
                        {
                            tokenSource.Token.ThrowIfCancellationRequested();                          
                            Automatic.Run(this.DataCenter);
                            Thread.Sleep(300);
                        }
                    }
                    catch (Exception ex)
                    {
                        this.ShowError(ex);
                    }

                    //使按钮可用
                    this.DisableControls(false);

                }, tokenSource.Token);
                #endregion
            };

            butStop.Click += (sender, e) =>
            {
                #region 停止
                if (tokenSource != null && !tokenSource.IsCancellationRequested)
                {
                    this.ShowMessage("停止");
                    tokenSource.Cancel();
                }

                #endregion
            };
        }
        #endregion


        public MainForm(DataCenter dataCenter)
        {
            this.Text += " v" + Assembly.GetExecutingAssembly().GetName().Version;
            this.DataCenter = dataCenter;
            InitializeComponent();




            this.cbMap.DataSource = new BindingSource() { DataSource = this.DataCenter.Maps };
            this.cbMap.DisplayMember = "Name";

            this.cbPlayer.DataSource = new BindingSource() { DataSource = this.DataCenter.Players };
            this.cbPlayer.DisplayMember = "DisplayString";
        }

        protected override void OnLoad(EventArgs e)
        {
            this.Location = new Point(Screen.PrimaryScreen.Bounds.Width - this.Width, 5);
            this.RegisterEvent();
            base.OnLoad(e);
        }

        public void ShowMessage(string message, params object[] obj)
        {
            string value = string.Empty;
            if (obj == null || obj.Length <= 0)
            {
                value = message;
            }
            else
            {
                value = string.Format(message, obj);
            }

            this.Invoke((UpdateInterface)delegate()
            {
                if (rbMessage.TextLength >= 50000)
                {
                    rbMessage.Clear();
                }
                rbMessage.AppendText(value + "\r\n");
            });

        }

        public void ShowError(Exception ex)
        {
            StringBuilder sb = new StringBuilder();

            if (ex is OperationCanceledException)
            {
                sb.AppendFormat("{0}:已经停止\r\n", DateTime.Now);
            }
            else if (ex is WindowException || ex is ArgumentException)
            {
                sb.AppendLine(DateTime.Now.ToString());
                sb.AppendLine("游戏大退");
            }
            else
            {
                sb.AppendLine("***异常信息***");
                sb.AppendLine("出现时间：");
                sb.AppendLine(DateTime.Now.ToString());
                sb.AppendLine("异常类型：");
                sb.AppendLine(ex.GetType().Name);
                sb.AppendLine("异常信息：");
                sb.AppendLine(ex.Message);
                sb.AppendLine("堆栈调用：");
                sb.AppendLine(ex.StackTrace);
                sb.AppendLine("***************");
            }

            this.Invoke((UpdateInterface)delegate()
            {
                int index = rbMessage.TextLength;
                rbMessage.AppendText(sb.ToString());
                rbMessage.Select(index, sb.Length);
                rbMessage.SelectionColor = Color.Red;
                rbMessage.Select(rbMessage.TextLength, 0);
            });
        }

        #region 初始化线程

        private Task InitLifeOrMagic(BarTypes barType)
        {
            CancellationTokenSource cts = null;
            if (barType == BarTypes.Life)
            {
                _CtsEatLife = new CancellationTokenSource();
                cts = _CtsEatLife;
            }
            else
            {
                _CtsEatMagic = new CancellationTokenSource();
                cts = _CtsEatMagic;
            }


            Task task = new Task(delegate()
            {
                Player player = this.DataCenter.CurrentPlayer;
                int cycleTime = 0;
                string message = string.Empty;
                string eatMessage = string.Empty;
                PictureBox picBox = null;
                if (barType == BarTypes.Life)
                {
                    cycleTime = this.DataCenter.Config.LifeCycleTime;
                    message = "获取生命";
                    eatMessage = "使用生命药水";
                    picBox = picLife;
                }
                else
                {
                    cycleTime = this.DataCenter.Config.MagicCycleTime;
                    message = "获取魔力";
                    eatMessage = "使用魔力药水";
                    picBox = picMagic;
                }

                try
                {
                    #region 内容
                    while (true)
                    {
                        if (cts.Token.IsCancellationRequested)
                        {
                            throw new OperationCanceledException(message, cts.Token);
                        }

                        Thread.Sleep(cycleTime);
                        _LifeAndmagicCount++;
                        if (_LifeAndmagicCount == 50 || _LifeAndmagicCount == 51)
                        {
                            this.ShowMessage(message);
                            if (_LifeAndmagicCount == 51)
                            {
                                _LifeAndmagicCount = 0;
                            }
                        }

                        bool isEat = PlayerAction.CheckLifeOrMagic(barType, this.DataCenter.CurrentPlayer);

                        this.Invoke((UpdateInterface)delegate()
                        {
                            picBox.Image = barType == BarTypes.Life
                                ? this.DataCenter.CurrentPlayer.Life.Image : this.DataCenter.CurrentPlayer.Magic.Image;
                        });

                        if (!isEat)
                        {
                            this.ShowMessage(eatMessage);
                            PlayerAction.EatDrug(barType == BarTypes.Life ? BarTypes.Life : BarTypes.Magic);
                        }
                    }
                    #endregion
                }
                catch (Exception ex)
                {
                    this.ShowError(ex);
                }
            }, cts.Token);

            return task;
        }

        private Task InitAttack(Map map, Player player)
        {
            _CtsAttack = new CancellationTokenSource();
            Task task = new Task(delegate()
            {
                int iStepLeft = 0;
                int iStepRight = 0;
                this.DisableControls(true);
                try
                {
                    #region 内容

                    IEnumerable<Skill> skills = this.DataCenter.CurrentPlayer.Skills.Where(t => t.Duration > 10000);
                    Step recent = null;
                    Step oldStep = null;
                    //判断位置                    
                    while (true)
                    {
                        if (_CtsAttack.Token.IsCancellationRequested)
                        {
                            throw new OperationCanceledException("自动攻击", _CtsAttack.Token);
                        }

                        //获取当前位置
                        this.ShowMessage("获取当前位置");
                        Point location = PlayerAction.FindPlayerLocation(map, this.DataCenter.Players.MapPoint);
                        this.Invoke((UpdateInterface)delegate()
                        {
                            if (this.picSmallMap.Image != null)
                            {
                                this.picSmallMap.Image.Dispose();
                            }
                            this.picSmallMap.Image = (Bitmap)map.Image.Clone();
                        });


                        //获取当前台阶
                        foreach (var step in map.Steps)
                        {
                            if (location.X >= step.Left.X && location.X <= step.Right.X
                                && location.Y <= step.Left.Y + 2 && location.Y >= step.Left.Y - 2)
                            {
                                recent = step;
                                break;
                            }
                        }



                        List<Directions> attack = new List<Directions>();
                        if (recent != null)
                        {
                            //判断台阶的位置
                            this.ShowMessage("初始方向检测");

                            if (oldStep != null && oldStep == recent)
                            {
                                attack.Add(Directions.Up);
                            }
                            else
                            {
                                oldStep = recent;
                                //根据连接点寻找初始方向
                                if (Math.Abs(recent.ConnectionPoint.X - recent.Left.X) >
                                    Math.Abs(recent.ConnectionPoint.X - recent.Right.X))
                                {
                                    attack.Add(Directions.Right);
                                    attack.Add(Directions.Left);
                                    attack.Add(Directions.Up);
                                }
                                else
                                {
                                    attack.Add(Directions.Left);
                                    attack.Add(Directions.Right);
                                    attack.Add(Directions.Up);
                                }
                            }
                        }
                        else
                        {
                            attack.Add(Directions.Down);
                        }

                        KeyCodes keyCode = KeyCodes.None;
                        foreach (var item in attack)
                        {

                            if (_CtsAttack.Token.IsCancellationRequested)
                            {
                                throw new OperationCanceledException("自动攻击", _CtsAttack.Token);
                            }
                            while (true)
                            {

                                if (_CtsAttack.Token.IsCancellationRequested)
                                {
                                    throw new OperationCanceledException("自动攻击", _CtsAttack.Token);
                                }

                                //找怪
                                using (Image<Gray, byte> full = LoliCode.Capture(this.DataCenter.Handle))
                                {
                                    //获取自身坐标
                                    List<Point> points = CvHelper.TemplateMatching(full, player.Mark1, 0.85);

                                    if (points.Count <= 0 && player.Mark2 != null)
                                    {
                                        points = CvHelper.TemplateMatching(full, player.Mark2, 0.85);
                                    }

                                    if (points.Count <= 0)
                                    {
                                        this.ShowMessage("未找到人物，等待2秒，跳一下");
                                        Thread.Sleep(1800);
                                        lock (this.DataCenter._KeyLock)
                                        {
                                            KeyCodes code = item == Directions.Left ? KeyCodes.Left : KeyCodes.Right;
                                            this.DataCenter.Action.KeyDown(code);
                                            Thread.Sleep(50);
                                            this.DataCenter.Action.KeyPress(KeyCodes.LMenu, 80);
                                            Thread.Sleep(50);
                                            this.DataCenter.Action.KeyUp(code);
                                        }

                                        continue;
                                    }

                                    Point point = points.FirstOrDefault();

                                    int height = 120;
                                    int width = 0;
                                    int x = 0;
                                    int y = point.Y - height;

                                    if (recent == null)
                                    {
                                        x = point.X - player.SkillRange < 0 ? 0 : point.X - player.SkillRange;
                                        width = point.X + player.SkillRange * 2 > 1024
                                            ? 1024 : point.X + player.SkillRange * 2;
                                    }
                                    else
                                    {
                                        //计算取点位置, //获取当前台阶大小
                                        int left = (location.X - recent.Left.X) * 15;
                                        int right = (recent.Right.X - location.X) * 15;
                                        x = point.X - left < 0 ? 0 : point.X - left;
                                        width = point.X + right > 1024 ? 1024 : point.X + right;
                                    }

                                    //this.ShowMessage(x + "," + y + "," + width + "," + height);

                                    //取图像
                                    Bitmap bmp = ImageHelper.Cut(full.Bitmap, x, y, width, height);

                                    this.DataCenter.MonsterImage = new Image<Gray, byte>(bmp);
                                    /*
                                    this.Invoke((UpdateInterface)delegate()
                                    {
                                        pictureBox1.Image = bmp.Clone(); ;
                                        //  bmp.Dispose();
                                    });
                                    */
                                    bmp.Dispose();

                                    List<Point> list = CvHelper.TemplateMatching(
                                        this.DataCenter.MonsterImage, map.MonsterMark, 0.9);

                                    //得到一堆怪物坐标
                                    //如果怪离得近

                                    int iLeft = 0;
                                    int iRight = 0;
                                    foreach (var monster in list)
                                    {
                                        if (monster.X - point.X > 0 && monster.X - point.X <= player.SkillRange)
                                        {
                                            iRight++;
                                        }
                                        else if (point.X - monster.X > 0 && point.X - monster.X <= player.SkillRange)
                                        {
                                            iLeft++;
                                        }
                                    }
                                    this.ShowMessage("检测到{0}个怪物\r\n能打到的左面{1}，右面{2}"
                                        , list.Count, iLeft, iRight);


                                    //单方向的人物
                                    if (player.SkillDirection == 1)
                                    {
                                        if (iLeft > 0)
                                        {
                                            lock (this.DataCenter._KeyLock)
                                            {
                                                this.DataCenter.Action.KeyPress(KeyCodes.Left, 80);
                                            }
                                            this.ShowMessage("打怪~");
                                            PlayerAction.Attack(this.DataCenter, skills);
                                        }

                                        if (iRight > 0)
                                        {
                                            lock (this.DataCenter._KeyLock)
                                            {
                                                this.DataCenter.Action.KeyPress(KeyCodes.Right, 80);
                                            }
                                            this.ShowMessage("打怪~");
                                            PlayerAction.Attack(this.DataCenter, skills);
                                        }
                                    }
                                    //双方向的人物
                                    else if (player.SkillDirection == 2 && (iLeft > 0 || iRight > 0))
                                    {
                                        if (iLeft > iRight)
                                        {
                                            lock (this.DataCenter._KeyLock)
                                            {
                                                this.DataCenter.Action.KeyPress(KeyCodes.Left, 80);
                                            }
                                        }
                                        else
                                        {

                                            lock (this.DataCenter._KeyLock)
                                            {
                                                this.DataCenter.Action.KeyPress(KeyCodes.Right, 80);
                                            }
                                        }
                                        this.ShowMessage("打怪~");
                                        PlayerAction.Attack(this.DataCenter, skills);
                                    }
                                }

                                //没找到台阶
                                if (recent == null)
                                {
                                    this.ShowMessage("未找到台阶,等待 {0} 毫秒！", this.DataCenter.Config.StepWaitTime);
                                    Thread.Sleep(this.DataCenter.Config.StepWaitTime);

                                    KeyCodes code = KeyCodes.None;
                                    if (iStepLeft++ <= 3)
                                    {
                                        this.ShowMessage("未找到台阶,左跳！");
                                        code = KeyCodes.Left;
                                    }
                                    else if (iStepRight <= 3)
                                    {
                                        this.ShowMessage("未找到台阶,右跳！");
                                        code = KeyCodes.Right;
                                    }
                                    else
                                    {
                                        iStepRight = 0;
                                        iStepLeft = 0;
                                    }
                                    lock (this.DataCenter._KeyLock)
                                    {
                                        this.DataCenter.Action.KeyDown(code);
                                        Thread.Sleep(100);
                                        this.DataCenter.Action.KeyPress(KeyCodes.LMenu, 50);
                                        Thread.Sleep(100);
                                        this.DataCenter.Action.KeyUp(code);
                                        Thread.Sleep(800);
                                    }
                                    break;
                                }

                                this.ShowMessage("往{0}走", item == Directions.Up ? "连接点" : item.ToString());
                                //走路
                                location = PlayerAction.FindPlayerLocation(map, this.DataCenter.Players.MapPoint);
                                //判断距离有多少
                                int distance = 0;

                                switch (item)
                                {
                                    case Directions.Up:
                                        int temp = recent.ConnectionPoint.X - location.X;
                                        if (temp < 0)
                                        {
                                            keyCode = KeyCodes.Left;
                                        }
                                        else
                                        {
                                            keyCode = KeyCodes.Right;
                                        }
                                        distance = Math.Abs(temp);
                                        break;
                                    case Directions.Down:
                                        break;
                                    case Directions.Left:
                                        distance = location.X - recent.Left.X;
                                        keyCode = KeyCodes.Left;
                                        break;
                                    case Directions.Right:
                                        distance = recent.Right.X - location.X;
                                        keyCode = KeyCodes.Right;
                                        break;
                                    default:
                                        break;
                                }


                                if (distance > this.DataCenter.Config.MoveDistance)
                                {
                                    distance = this.DataCenter.Config.MoveDistance;
                                }

                                //捡东西 边走边检东西
                                lock (this.DataCenter._KeyLock)
                                {
                                    this.DataCenter.Action.KeyDown(keyCode);
                                    Thread.Sleep(5);
                                    //计算捡东西的次数
                                    int len = distance *
                                        this.DataCenter.Config.KeyRate / this.DataCenter.Config.PickCycleTime;

                                    if (len <= 0)
                                    {
                                        switch (distance)
                                        {
                                            case 1:
                                                Thread.Sleep(30);
                                                break;
                                            case 2:
                                                Thread.Sleep(50);
                                                break;
                                            default:
                                                Thread.Sleep(80);
                                                break;
                                        }

                                    }
                                    else
                                    {

                                        for (int i = 0; i < len; i++)
                                        {
                                            this.DataCenter.Action.KeyPress(
                                                KeyCodes.Z, this.DataCenter.Config.PickCycleTime);
                                        }
                                    }
                                    Thread.Sleep(5);
                                    this.DataCenter.Action.KeyUp(keyCode);
                                }


                                //走到头了，break；
                                location = PlayerAction.FindPlayerLocation(map, this.DataCenter.Players.MapPoint);


                                if (location.Y != recent.Left.Y || location.X > recent.Right.X || location.X < recent.Left.X)
                                {
                                    this.ShowMessage("台阶有变化，重新寻找");
                                    recent = null;
                                    break;
                                }

                                if (item == Directions.Left)
                                {
                                    if (location.X <= recent.Left.X + 3)
                                    {
                                        this.ShowMessage("左侧到头了~");
                                        break;
                                    }
                                }
                                else if (item == Directions.Right)
                                {
                                    if (location.X >= recent.Right.X - 3)
                                    {
                                        this.ShowMessage("右侧到头了~");
                                        break;
                                    }
                                }
                                else if (item == Directions.Up)
                                {
                                    #region 连接点
                                    KeyCodes cKeyCode = KeyCodes.None;
                                    bool isMove = false;

                                    // this.ShowMessage("开始移动到连接点{0}", code);
                                    switch (recent.ConnectionPointMode)
                                    {
                                        case Directions.Up:
                                            cKeyCode = KeyCodes.Up;
                                            isMove = location.ToString() == recent.ConnectionPoint.ToString();
                                            break;
                                        case Directions.Down:
                                            cKeyCode = KeyCodes.Down;
                                            isMove = Math.Abs(location.X - recent.ConnectionPoint.X) <= 2;
                                            break;
                                        case Directions.Left:
                                            cKeyCode = KeyCodes.Left;
                                            isMove = location.X - recent.ConnectionPoint.X <= 1;
                                            break;
                                        case Directions.Right:
                                            cKeyCode = KeyCodes.Right;
                                            isMove = recent.ConnectionPoint.X - location.X <= 1;
                                            break;
                                    }

                                    Thread.Sleep(500);

                                    if (isMove)
                                    {
                                        this.ShowMessage("开始移动到下一台阶");
                                        lock (this.DataCenter._KeyLock)
                                        {
                                            Thread.Sleep(200);
                                            this.DataCenter.Action.KeyDown(cKeyCode);
                                            Thread.Sleep(50);
                                            if (recent.IsJump)
                                            {
                                                this.DataCenter.Action.KeyPress(KeyCodes.LMenu, 100);
                                                if (recent.Duration != 0)
                                                {
                                                    Thread.Sleep(50);
                                                    this.DataCenter.Action.KeyUp(cKeyCode);
                                                    Thread.Sleep(50);
                                                    this.DataCenter.Action.KeyDown(cKeyCode);
                                                    if (recent.Duration > 0)
                                                    {
                                                        Thread.Sleep(recent.Duration);
                                                    }
                                                }
                                            }
                                            Thread.Sleep(50);
                                            this.DataCenter.Action.KeyUp(cKeyCode);
                                            this.ShowMessage("移动完成");
                                            recent = null;
                                            break;
                                        }

                                    }
                                    #endregion
                                }

                                if (recent == null)
                                {
                                    break;
                                }
                            }
                        }
                    }
                    #endregion
                }
                catch (Exception ex)
                {
                    this.ShowError(ex);
                }
                finally
                {
                    this.DisableControls(false);
                }
            }, _CtsAttack.Token);

            return task;
        }

        private Task InitBuff()
        {
            Task task = new Task(delegate()
            {
                //建立Buff计时器
                foreach (var item in this.DataCenter.CurrentPlayer.Skills.Where(t => t.Duration >= 10000))
                {
                    this.ShowMessage("创建Buff计时器 {0}", item.KeyCode);

                    System.Timers.Timer timer = new System.Timers.Timer();
                    timer.Interval = item.Duration < 10000 ? item.Duration * 1000 : item.Duration;
                    timer.AutoReset = true;

                    timer.Start();
                    _BuffTimer.Add(timer);

                    timer.Elapsed += (tSender, tE) =>
                    {
                        this.ShowMessage("加Buff {0}", item.KeyCode);

                        //锁定其他buff持续时间
                        lock (this.DataCenter._SkillLock)
                        {
                            //执行按键
                            lock (this.DataCenter._KeyLock)
                            {
                                Thread.Sleep(500);
                                this.DataCenter.Action.KeyPress(item.KeyCode, 80);
                            }
                            Thread.Sleep(item.ActionTime);
                        }
                    };


                    this.ShowMessage("加Buff {0}", item.KeyCode);
                    //先执行一次
                    lock (this.DataCenter._KeyLock)
                    {
                        this.DataCenter.Action.KeyPress(item.KeyCode, 80);
                    }
                    Thread.Sleep(2000);
                }
            });
            return task;
        }

        private Task InitAlarm()
        {

            Task task = new Task(delegate()
            {
                while (true)
                {


                    bool isOffline = false;
                    IntPtr handle = MapleStory.FindWindow();
                    if (handle == IntPtr.Zero)
                    {
                        this.ShowMessage("游戏掉线");
                        isOffline = true;
                    }

                    if (!isOffline)
                    {

                        var rect = new Bear.Library.WinApi.Rect();
                        WinApiHelper.GetWindowRect(handle, ref rect);
                        //检测大小
                        if (rect.Right - rect.Left < 900)
                        {
                            this.ShowMessage("游戏小退");
                            isOffline = true;
                        }
                    }

                    try
                    {
                        using (Image<Gray, byte> full = LoliCode.Capture())
                        {
                            //this.ShowMessage("验证码检测");
                            //检测验证码
                            List<Point> list = CvHelper.TemplateMatching(full, this.DataCenter.VerificationImage, 0.8);
                            if (list.Count > 0)
                            {
                                this.ShowMessage("验证码来了");

                                if (this.DataCenter.Config.IsVerificationOffline)
                                {
                                    lock (this.DataCenter._KeyLock)
                                    {
                                        this.DataCenter.Action.KeyPress(KeyCodes.Escape, 100);
                                        Thread.Sleep(300);
                                        this.DataCenter.Action.KeyPress(KeyCodes.Up, 100);
                                        Thread.Sleep(300);
                                        this.DataCenter.Action.KeyPress(KeyCodes.Enter, 100);
                                    }
                                }

                            }
                            //检测死亡
                            list = CvHelper.TemplateMatching(full, this.DataCenter.DeathImage, 0.8);
                            if (list.Count > 0)
                            {
                                this.ShowMessage("人物死亡");
                            }
                        }
                    }
                    catch (Exception)
                    {

                        // throw;
                    }



                    Thread.Sleep(this.DataCenter.Config.AlarmInterval);
                }

            });
            return task;
        }

        #endregion

        #region 功能按钮

        private void butStart_Click(object sender, EventArgs e)
        {
            //this.DataCenter.CurrentMap = map;
            //this.DataCenter.CurrentPlayer = player;

            //this.ShowMessage("初始化建模");
            //map.MonsterMark = new Image<Gray, byte>("Datas\\" + map.MonsterMarkName + ".mst");
            //player.Mark1 = new Image<Gray, byte>("Datas\\" + player.MarkName1 + ".ply");
            //if (!string.IsNullOrEmpty(player.MarkName2))
            //{
            //    player.Mark2 = new Image<Gray, byte>("Datas\\" + player.MarkName2 + ".ply");
            //}



            //IntPtr handle = MapleStory.FindWindow();

            //if (handle == IntPtr.Zero)
            //{
            //    LoliMessageBox.Show(this, "请先开启游戏！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    return;
            //}

            //this.DataCenter.Handle = handle;


            //WinApiHelper.ShowWindow(handle, 1);
            //WinApiHelper.SetForegroundWindow(handle);
            //Thread.Sleep(500);


            //Task 吃红 = this.InitLifeOrMagic(BarTypes.Life);
            //Task 吃蓝 = this.InitLifeOrMagic(BarTypes.Magic);
            //Task 打怪 = this.InitAttack(map, player);
            //Task 增益 = this.InitBuff();
            //Task 报警 = this.InitAlarm();

            //增益.Start();
            //吃蓝.Start();
            //吃红.Start();
            //打怪.Start();
            //报警.Start();
            //   拾取.Start();
            // 打怪.Start();
        }

        private void butStop_Click(object sender, EventArgs e)
        {
            if (this._CtsEatLife != null)
            {
                this._CtsEatLife.Cancel();
            }

            if (this._CtsEatMagic != null)
            {
                this._CtsEatMagic.Cancel();
            }




            if (this._CtsAttack != null)
            {
                this._CtsAttack.Cancel();
            }


            foreach (var item in _BuffTimer)
            {
                item.Stop();
            }

            this._BuffTimer.Clear();


            this.ShowMessage("停止");
        }

        private void DisableControls(bool isDisabled)
        {
            foreach (Control item in this.Controls)
            {
                this.Invoke((UpdateInterface)delegate()
                {
                    if (item is TextBox || item is ComboBox)
                    {
                        item.Enabled = !isDisabled;
                    }
                    else if (item is Button && item.Text != "停止")
                    {
                        item.Enabled = !isDisabled;
                    }
                });
            }
        }

        private void miOption_Click(object sender, EventArgs e)
        {
            if (_OptionForm == null)
            {
                _OptionForm = new OptionForm();
            }

            DialogResult result = _OptionForm.ShowDialog(this);
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                //如果更改了，那么初始化新的下拉框
                (this.cbPlayer.DataSource as BindingSource).ResetBindings(true);
                (this.cbMap.DataSource as BindingSource).ResetBindings(true);
            }
        }

        private void miAbout_Click(object sender, EventArgs e)
        {
            if (_AboutForm == null)
            {
                _AboutForm = new AboutBox();
            }

            _AboutForm.ShowDialog(this);
        }
        private void miMachineCode_Click(object sender, EventArgs e)
        {
            MachineCodeForm MachineCodeForm = new MachineCodeForm();
            MachineCodeForm.ShowDialog();
        }



        private void miExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #endregion



    }
}